﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using Common;
using log4net;
using AutoFacUtils;
using CashFlow.Web.Def;
using CashFlow.Web.Service;
using CashFlow.Web.Models.Account;
using CashFlow.Web.Validator.Account;
using CashFlow.Web.MyActionResult;
using CashFlow.Web.Filters;
using CashFlow.Web.Common;

namespace CashFlow.Web.Controllers
{
    [AllowAnonymous]
    [NotLoginFilter]
    public class AccountController : Controller
    {
        private static readonly ILog _logger = LogManager.GetLogger(typeof(AccountController));
        private IUserService GetUserService() { return AutoFacHelper.Get<IUserService>(); }

        public ActionResult Register()
        {
            return View();
        }

        [HttpPost]
        [ValidatorFilter(typeof(RegisterUserInfoModelValidator))]
        public ActionResult Register(RegisterUserInfoModel model)
        {
            bool success = false;
            string msg = "";
            if (Session[Consts.SessionKey_VerityCode] != null
                && Session[Consts.SessionKey_VerityCode].ToString().ToLower() == model.VerifyCode.ToLower())
            {
                var service = GetUserService();
                var result = service.Register(model.Phone
                                , model.Pwd
                                , model.Name
                                , model.ReferenceInvitationCode
                             );
                success = result == ERegisterResult.Success;
                msg = EnumTool.GetDescription<ERegisterResult, int>(result);
            }
            else
            {
                msg = "验证码不正确！";
            }

            return MyCommonTool.CreateOperationResult(success, msg, null);
        }

        public ActionResult Login()
        {
            return View();
        }

        [HttpPost]
        [ValidatorFilter(typeof(LoginUserInfoModelValidator))]
        public ActionResult Login(LoginUserInfoModel model)
        {
            var service = GetUserService();
            var result = service.Login(model.Phone, model.Pwd);
            string msg = EnumTool.GetDescription<ELoginResult, int>(result);
            return MyCommonTool.CreateOperationResult(
                        result == ELoginResult.Success
                        , msg
                        , ""
                   );
        }

        public ActionResult VertifyCode()
        {
            string code = "";
            byte[] buf = VerifyCodeHelper.GetVerifyCode(out code);
            Session[Consts.SessionKey_VerityCode] = code;
            FileContentResult tcr = new FileContentResult(buf, "image/jpeg");
            return tcr;
        }
    }
}